import React, { useState, useEffect } from 'react';
import { List, Card, Typography, Button, Alert, Spin, Tag, Collapse } from 'antd';
import axios from 'axios';

const { Title, Paragraph } = Typography;
const { Panel } = Collapse;

const TeacherView = () => {
  const [questions, setQuestions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [categorizing, setCategorizing] = useState(false);

  // 获取问题列表
  const fetchQuestions = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:5000/api/questions');
      setQuestions(response.data);
      setError(null);
    } catch (err) {
      setError('获取问题列表失败: ' + err.message);
      console.error('获取问题失败:', err);
    } finally {
      setLoading(false);
    }
  };

  // 分类问题
  const categorizeQuestions = async () => {
    try {
      setCategorizing(true);
      setError(null);
      
      const response = await axios.post('http://localhost:5000/api/categorize', {
        questions: questions
      });

      if (response.data && response.data.questions) {
        setQuestions(response.data.questions);
      }
    } catch (err) {
      setError('问题分类失败: ' + err.message);
      console.error('分类失败:', err);
    } finally {
      setCategorizing(false);
    }
  };

  // 获取分类颜色
  const getCategoryColor = (category) => {
    const colors = {
      '知识点定义类问题': 'blue',
      '知识点应用类问题': 'green',
      '知识点关联类问题': 'purple',
      '解题方法类问题': 'orange',
      '实验操作类问题': 'cyan',
      '知识拓展类问题': 'magenta',
      '其他类问题': 'default'
    };
    return colors[category] || 'default';
  };

  // 格式化分析内容
  const formatAnalysis = (analysis) => {
    if (!analysis) return null;
    
    return (
      <Collapse defaultActiveKey={['1']}>
        <Panel header="问题分析" key="1">
          <Paragraph>
            <strong>核心知识点：</strong>
            {analysis.coreKnowledge || '暂无分析'}
          </Paragraph>
          <Paragraph>
            <strong>学习路径：</strong>
            {analysis.learningPath || '暂无分析'}
          </Paragraph>
          <Paragraph>
            <strong>理解难点：</strong>
            {analysis.difficulty || '暂无分析'}
          </Paragraph>
          <Paragraph>
            <strong>解答思路：</strong>
            {analysis.solution || '暂无分析'}
          </Paragraph>
          <Paragraph>
            <strong>扩展知识：</strong>
            {analysis.extension || '暂无分析'}
          </Paragraph>
          <Paragraph>
            <strong>教学建议：</strong>
            {analysis.suggestion || '暂无分析'}
          </Paragraph>
        </Panel>
      </Collapse>
    );
  };

  useEffect(() => {
    fetchQuestions();
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>学生问题列表</Title>
      
      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: '16px' }}
        />
      )}

      <div style={{ marginBottom: '16px' }}>
        <Button 
          type="primary" 
          onClick={categorizeQuestions}
          loading={categorizing}
          disabled={questions.length === 0}
        >
          问题分类
        </Button>
      </div>

      {loading ? (
        <Spin size="large" />
      ) : (
        <List
          grid={{ gutter: 16, column: 1 }}
          dataSource={questions}
          renderItem={question => (
            <List.Item>
              <Card 
                title={
                  <div>
                    <span>{question.studentName} ({question.studentId})</span>
                    {question.category && (
                      <Tag color={getCategoryColor(question.category)} style={{ marginLeft: '8px' }}>
                        {question.category}
                      </Tag>
                    )}
                  </div>
                }
                extra={
                  <span>
                    {new Date(question.timestamp).toLocaleString()}
                  </span>
                }
              >
                <Paragraph strong>问题内容：</Paragraph>
                <Paragraph>{question.content}</Paragraph>
                
                {formatAnalysis(question.analysis)}
              </Card>
            </List.Item>
          )}
        />
      )}
    </div>
  );
};

export default TeacherView; 